//
//  MineViewController.m
//  LiveSoftware
//
//  Created by lanou3g on 15/7/24.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "MineViewController.h"

#import "suggestViewController.h"

#import "AboutUSViewController.h"

#import "SwitchViewCell.h"
@interface MineViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)UITableView *mineSettingTableView;
//@property(nonatomic,strong)

@property(nonatomic,strong)NSArray * stringArray;

@property(nonatomic)float filesSize;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self customNavigationBar];

    //清除缓存
    //建议反馈
    //检查更新
    //仅在wifi下观看视频
    //关于
    //当前版本
    
  
    
    self.mineSettingTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    
    
    self.mineSettingTableView.delegate = self;
    self.mineSettingTableView.dataSource = self;
   self.mineSettingTableView.scrollEnabled = NO;
    
    
    [self.view addSubview:_mineSettingTableView];
    self. stringArray = @[@"清除缓存",@"关于"];

}


//几个分区
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark  多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 4;
}


#pragma mark  returnCell
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *cellIndenfier = @"mineSetting";
        UITableViewCell *cell= [tableView  dequeueReusableCellWithIdentifier:cellIndenfier];
    
    cell.backgroundColor = [UIColor clearColor];
    if(cell ==nil)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndenfier];
        }
    cell.selectionStyle =UITableViewCellSelectionStyleNone;

    if (indexPath.row == 0) {
        static NSString *cellInde = @"swithCell";
        [tableView registerClass:[SwitchViewCell class] forCellReuseIdentifier:cellInde];
        
        
        SwitchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInde forIndexPath:indexPath];
        
        
        
        
        [cell.swWifi addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
       
        cell.label.text = @"仅在WiFi下观看视频";
        [cell.contentView addSubview:cell.swWifi];
        
        
        //
        NSString * state = [[NSUserDefaults standardUserDefaults]objectForKey:@"state"];
        
        if ([state isEqualToString:@"YES"])//如果是yes
        {
            [cell.swWifi setOn:YES animated:NO];

        }
        else
        {
            cell.swWifi.on = NO;
        }

        
        
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    
    
    else if(indexPath.row==1)
        {
            static NSString *cellInde = @"banben";
            [tableView registerClass:[SwitchViewCell class] forCellReuseIdentifier:cellInde];
  
            SwitchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInde forIndexPath:indexPath];

            cell.label.text = @"当前版本";
            
            //获取当前版本
            NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
            
            NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
            
            cell.banBen.text = appVersion;
            cell.banBen.textAlignment = NSTextAlignmentCenter;
            
            [cell.contentView addSubview:cell.banBen];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
                 
            return cell;
        }
    else if (indexPath.row == 2)
        {
            static NSString *cellInde = @"huancun";
            [tableView registerClass:[SwitchViewCell class] forCellReuseIdentifier:cellInde];
            
            SwitchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInde forIndexPath:indexPath];
            NSString *theCachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
            
            
            float size = [self folderSizeAtPath:theCachePath];

            NSString *message = [NSString stringWithFormat:@"%.1fM",size];
            cell.huancun.text = message;
            cell.huancun.textAlignment = NSTextAlignmentCenter;
            cell.label.text = @"清除缓存";
            [cell.contentView addSubview:cell.huancun];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;

        }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel .text = self.stringArray[indexPath.row - 2];
        return cell;
    }

}


#pragma mark  点击
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        if(indexPath.row==2)
        {
//            NSString *theCachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
//            
            
            
//            float size = [self folderSizeAtPath:theCachePath];
            
//            NSString *message = [NSString stringWithFormat:@"缓存大小为%.1fM,确定删除吗?",size];
            NSString *message = [NSString stringWithFormat:@"确定清除缓存？"];
            
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alertView show];
            //[self.mineSettingTableView reloadData];
            
        }
       
        else if(indexPath.row ==3)
        {
            AboutUSViewController *aboutUSVC= [[AboutUSViewController alloc]init];
            [self.navigationController pushViewController:aboutUSVC animated:YES];
        }else
        {
        }
}

#pragma mark - headerView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return kScreenIp6(150);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenIp6(150), kScreenIp6(150))];

    UIImageView *myHeaderBackImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth/2 -kScreenIp6(50), kScreenIp6(25), kScreenIp6(100), kScreenIp6(100))];
    myHeaderBackImageView.image = [UIImage imageNamed:@"Live＋"];
    [headerView addSubview:myHeaderBackImageView];
    
//    
//    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    CGFloat backButtonW = kScreenIp6(100);
//    CGFloat backButtonX = (kScreenWidth - backButtonW) / 2;
//    CGFloat backButtonY = (myHeaderBackImageView.frame.size.height - backButtonW) / 2;
//
//    backButton.frame = CGRectMake(backButtonX, backButtonY, backButtonW, backButtonW);
//    backButton.layer.cornerRadius = backButtonW / 2;
//    [backButton setBackgroundImage:[UIImage imageNamed:@"football_collected_small"] forState:UIControlStateNormal];
//    [myHeaderBackImageView addSubview:backButton];
    
    return headerView;
}

-(void)switchAction:(UISwitch*)sender
{
    
    if (sender.on)
    {
        [MBProgressHUD showSuccess:@"仅在WiFi条件下观看视频"];
        [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"state"];
    }
    else
    {
        [MBProgressHUD showSuccess:@"所有网络都可以观看视频"];
        [[NSUserDefaults standardUserDefaults]setObject:@"NO" forKey:@"state"];
    }
}


#pragma mark  提示框
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1)
    {
        [self clearCaches];

        [self.mineSettingTableView reloadData];
    }
   

}

#pragma mark  清除缓存
//查看缓存文件多少M

-(long long)fileSizeAtPath:(NSString *)filePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if([manager fileExistsAtPath:filePath])
       {
           
           
           return [[manager attributesOfItemAtPath:filePath error:nil]fileSize];
           
           
       }
    
    
    return 0;
    
}



//遍历文件夹获得文件夹大小,返回多少M
-(float)folderSizeAtPath:(NSString*)folderPath
{
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if(![manager  fileExistsAtPath:folderPath])return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath]objectEnumerator];
    
    NSString *fileName;
    long long folderSize =0;
    
    
    while ( (fileName =[childFilesEnumerator nextObject])!= nil)
    {
        
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
        
    }
    return folderSize/(1024.0 *1024.0);

}


//清除缓存
-(void)clearCaches
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSLog(@"cach----%@",cachPath);
    
    
    NSArray *files = [[NSFileManager defaultManager]subpathsAtPath:cachPath];
    NSLog(@"files=======%ld",[files count]);
    
   
    
    for (NSString *pfile in files )
    {
        NSError *error;
        NSString *path = [cachPath stringByAppendingPathComponent:pfile ];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path])
        {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
    
[self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}



-(void)clearCacheSuccess
{
    [MBProgressHUD  showSuccess:@"清除成功"];
}



#pragma mark - 隐藏和显示导航栏
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
#pragma mark - 自定义导航栏
- (void)customNavigationBar
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"header_bg_green_2@2x"] forBarMetrics:UIBarMetricsDefault];
    
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"set_arrow_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popback)];
    [backBarButton setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBarButton;
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenIp6(50), kScreenIp6(30))];
    title.text = @"菜单";
    title.textColor = [UIColor whiteColor];
    [self.navigationItem setTitleView:title];
}

- (void)popback
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}

@end
